# -*- coding: utf-8 -*-
#
# Tubemaster
#
# Copyright (C) 2009 Selim Ok <selimok@gmail.com>
# Copyright (C) 2007-2008 Siegfried-Angel Gevatter Pujals <siggi.gevatter@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

# Tubemaster Preferences
# This file contains all classes / functions needed to save and retrieve the preferences
# and also those concerning the Preferences window.
# It also handles other stuff related with INI files.

from PyQt4 import QtCore, QtGui

try:
	import pynotify
	pynotify_is_available = True
except ImportError:
	pynotify_is_available = False

def loadSettings():
	"""Returns a QSettings instance and, if needed, populates it with the default settings."""
	
	settings = QtCore.QSettings(QtCore.QSettings.IniFormat, QtCore.QSettings.UserScope, 'Tubemaster', 'tubemaster')
	
	if (not settings.contains('General/version')) or settings.value('General/version').toInt() < 0.2:
		defaultSettings(settings)
	
	return settings

def defaultSettings(settings):
	"""Overwrittes a QSettings instance with all default settings."""
	
	from os.path import expanduser
	
	settings.clear()	# Delete everything from the file
	
	settings.beginGroup('General')
	settings.setValue('version', QtCore.QVariant(0.2))
	settings.setValue('folder', QtCore.QVariant(expanduser('~')))
	settings.setValue('script', QtCore.QVariant('youtube-dl'))
	settings.setValue('spaces', QtCore.QVariant(2))
	settings.endGroup()
	
	settings.beginGroup('Interface')
	settings.setValue('beep', QtCore.QVariant(2))
	settings.setValue('startMinimal', QtCore.QVariant(2))
	settings.setValue('effectExpand', QtCore.QVariant(2))
	if pynotify_is_available is True:
		settings.setValue('notifyDone', QtCore.QVariant(2))
		settings.setValue('notifyError', QtCore.QVariant(2))
	else:
		settings.setValue('notifyDone', QtCore.QVariant(0))
		settings.setValue('notifyError', QtCore.QVariant(0))
	settings.endGroup()

def selectFolder(this, value):
	"""Shows a folder selection dialog and returns the path to the selected one (or false)."""
	
	folder = QtGui.QFileDialog.getExistingDirectory(this,
				this.tr("Select the destination folder"),
				value,
				QtGui.QFileDialog.ShowDirsOnly | QtGui.QFileDialog.DontResolveSymlinks
			);
	
	return folder

def getCheckState(value):
	"""Converts a integer (accepted values are: 0, 1, 2) to a CheckState."""
	
	try:
		value = value[0]
	except TypeError:
		pass
	
	return QtCore.Qt.CheckState(value)
	

class PreferencesGui(QtGui.QDialog):
	"""The class responsible for the Preferences window."""
	
	def __init__(self, parent, settings):
		"""Initialize the GUI."""
		
		from ui_preferences import Ui_PreferencesWindow
		
		QtGui.QDialog.__init__(self, parent)
		self.ui = Ui_PreferencesWindow()
		self.ui.setupUi(self)
		
		self.settings = settings
		self.parent = parent
		
		# Update the window to display the corrent configuration
		self.ui.s_folder.setText(self.settings.value('General/folder').toString())
		self.ui.s_script.setText(self.settings.value('General/script').toString())
		self.ui.s_spaces.setCheckState(getCheckState(self.settings.value('General/spaces').toInt()))
		self.ui.s_beep.setCheckState(getCheckState(self.settings.value('Interface/beep').toInt()))
		self.ui.s_startMinimal.setCheckState(getCheckState(self.settings.value('Interface/startMinimal').toInt()))
		self.ui.s_effectExpand.setCheckState(getCheckState(self.settings.value('Interface/effectExpand').toInt()))
		self.ui.s_notifyDone.setCheckState(getCheckState(self.settings.value('Interface/notifyDone').toInt()))
		self.ui.s_notifyError.setCheckState(getCheckState(self.settings.value('Interface/notifyError').toInt()))
		
		if pynotify_is_available is not True:
			self.ui.stackNotify.setCurrentIndex(1)
		
		# Connect signals with slots
		QtCore.QObject.connect(self.ui.button_folder, QtCore.SIGNAL("clicked()"), self.browseFolder)
		QtCore.QObject.connect(self.ui.buttonBox, QtCore.SIGNAL("accepted()"), self.saveSettings)
		QtCore.QObject.connect(self.ui.buttonApply, QtCore.SIGNAL("clicked()"), self.saveSettings)
		
	def browseFolder(self):
		"""Shows a folder selection dialog and (if the user doesn't cancel it) sets the new destination in the input."""
		
		folder = selectFolder(self, self.ui.s_folder.text())
		
		if folder:
			self.ui.s_folder.setText(folder)
		
	def saveSettings(self):
		"""Saves the settings."""
		
		self.settings.setValue('General/folder', QtCore.QVariant(self.ui.s_folder.text()))
		self.settings.setValue('General/script', QtCore.QVariant(self.ui.s_script.text()))
		self.settings.setValue('General/spaces', QtCore.QVariant(int(self.ui.s_spaces.checkState())))
		self.settings.setValue('Interface/beep', QtCore.QVariant(int(self.ui.s_beep.checkState())))
		self.settings.setValue('Interface/startMinimal', QtCore.QVariant(int(self.ui.s_startMinimal.checkState())))
		self.settings.setValue('Interface/effectExpand', QtCore.QVariant(int(self.ui.s_effectExpand.checkState())))
		self.settings.setValue('Interface/notifyDone', QtCore.QVariant(int(self.ui.s_notifyDone.checkState())))
		self.settings.setValue('Interface/notifyError', QtCore.QVariant(int(self.ui.s_notifyError.checkState())))
		self.settings.sync()
		
		self.parent.settings.sync()
		self.parent.adjustInputs(updatedSettings=True)
